using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.EntityFrameworkCore;
using MoMing.VideoTool.Downloader.Model;

namespace MoMing.VideoTool.Downloader.Apis
{
    public static class DownLoaderApi
    {
        public static IEndpointRouteBuilder MapDownloaderApiV1(this IEndpointRouteBuilder app)
        {
            var api = app.MapGroup("/api/v1/downloader").HasApiVersion(1.0);
            api.MapPost("download/{url}", DownloadAsync);
            api.MapGet("logs", GetDownloadLogsAsync);
            return app;
        }

        public static async Task<Ok<string>> DownloadAsync([AsParameters] DownLoaderServices downLoaderServices, string url)
        {
            var videoId = string.Empty;
            var isDownload = await downLoaderServices.Context.DownloadLogs.AnyAsync(x => x.VideoId == videoId);
            if (isDownload)
                return TypedResults.Ok("this video is downloading");
            var downloadLog = new DownloadLog(videoId, "","", "", "");
            await downLoaderServices.Context.DownloadLogs.AddAsync(downloadLog);
            return TypedResults.Ok("downloading");
        }
        public static async Task<Ok<PaginatedItems<DownloadLog>>> GetDownloadLogsAsync([AsParameters] DownLoaderServices downLoaderServices, [AsParameters] PaginationRequest paginationRequest)
        {
            var queryable = downLoaderServices.Context.DownloadLogs;
            var logs = await queryable
            .Skip(paginationRequest.PageSize * (paginationRequest.PageIndex))
            .Take(paginationRequest.PageSize).ToListAsync();
            var total = await queryable.LongCountAsync();
            return TypedResults.Ok(new PaginatedItems<DownloadLog>(paginationRequest.PageIndex, paginationRequest.PageSize, total, logs));
        }
    }
}